package com.molyfun.parents;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadHelper;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.molyfun.parents.activity.common.ShareDialogActivity;
import com.molyfun.parents.dao.entity.SingleDownloadTask;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleDownloadTaskDao;
import com.molyfun.parents.im.MyIMOfflinePushListener;
import com.molyfun.parents.rest.QiniuSDK;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.service.filedownload.CourseDownLoadUtils;
import com.molyfun.parents.uievent.EventController;
import com.molyfun.parents.uievent.EventDispatcher;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.FileUtils;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.NetWorkUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.Tools;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.yilin.parents.wxapi.WXEntryActivity;

import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class MFPApplication extends MultiDexApplication {
	public static MFPApplication sInstance;

	public static String sVersionName;

	public static String cacheDir;
	public static String cameraDir;

	public static float sDensity;
	public static int sScreenWidth;
	public static int sScreenHeight;

	private RestClient mRestClient;

	private static String user_agent;

	private UserResponse.User mUser;
	private QiniuSDK mQiniuSDK;

	private SingleDownloadTaskDao singleDownloadTaskDao;
	private EventDispatcher mEventDispatcher;
	private EventController mEventController;
	public static IWXAPI sApi;
	public static boolean isEmui = false;
	@Override
	public void onCreate() {
		super.onCreate();
		sInstance = this;
		// 注册crashHandler
//		CrashHandler crashHandler = CrashHandler.getInstance();
//		crashHandler.setCrashHandler(MFPApplication.getInstance());
		mQiniuSDK = new QiniuSDK();
		sVersionName = Tools.getAppVersionName(this);

		mEventController = EventController.getInstance();
		mEventDispatcher = EventDispatcher.getInstance(mEventController);

		SpeechUtility.createUtility(MFPApplication.this, SpeechConstant.APPID + "=57dfd3a6");

		//初始化数据
		DisplayMetrics mDisplayMetrics = getResources().getDisplayMetrics();
		sScreenWidth = mDisplayMetrics.widthPixels;
		sScreenHeight = mDisplayMetrics.heightPixels;
		sDensity = mDisplayMetrics.density;

		cacheDir = new FileUtils(this).makeAppDir();
		FileDownloadUtils.setDefaultSaveRootPath(FileUtils.COURSECACHEPATH);
		cameraDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
				+ "/Camera";

		//获取user-agent
		StringBuilder sb = new StringBuilder();
		sb.append("MFParents/");
		try {
			PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			sb.append(pInfo.versionName);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		sb.append("(Android;");
		sb.append(android.os.Build.VERSION.RELEASE + ";");
		sb.append(android.os.Build.MODEL + ")");
		user_agent = sb.toString();

		String token = PreferencesStorageUtil.getToken(this);
		//初始化网络
		mRestClient = new RestClient(token, user_agent);

		//配置下载参数
		FileDownloader.init(getApplicationContext(),
				new FileDownloadHelper.OkHttpClientCustomMaker() { // is not has to provide.
					@Override
					public OkHttpClient customMake() {
						// just for OkHttpClient customize.
						final OkHttpClient.Builder builder = new OkHttpClient.Builder();
						// you can set the connection timeout.
						builder.connectTimeout(15_000, TimeUnit.MILLISECONDS);
						// you can set the HTTP proxy.
						builder.proxy(Proxy.NO_PROXY);
						// etc.
						return builder.build();
					}
				});


		//下载未完成任务
		DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
		DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
		DaoSession daoSession = daoMaster.newSession();
		singleDownloadTaskDao = daoSession.getSingleDownloadTaskDao();
		List<SingleDownloadTask> singleDownloadTaskList = singleDownloadTaskDao.queryBuilder().where(SingleDownloadTaskDao.Properties.State.eq(Const.DOWNLOAD_STATE_FAILED)).build().list();
		if(singleDownloadTaskList != null && singleDownloadTaskList.size() > 0 && NetWorkUtil.isInWifiNetWork(this)) {
			CourseDownLoadUtils.startDownLoadFiledMedia(this, (ArrayList)singleDownloadTaskList);
		}

		sApi = WXEntryActivity.initWeiXin(this, ShareDialogActivity.WX_APP_ID);

		//腾讯IM初始化SDK基本配置
		TIMSdkConfig config = new TIMSdkConfig(1400064002)
				.setAccoutType("20730")
				.enableCrashReport(false)
				.enableLogPrint(true)
				.setLogLevel(TIMLogLevel.DEBUG)
				.setLogPath(FileUtils.SDPATH + "/log/");
		//初始化SDK
		TIMManager.getInstance().init(sInstance, config);
		TIMManager.getInstance().setUserConfig(new TIMUserConfig());
		TIMManager.getInstance().setOfflinePushListener(new MyIMOfflinePushListener(sInstance));
//		isEmui = OSHelper.isEMUI();
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}

	public void setUser(UserResponse.User user){
		this.mUser = user;
	}

	public UserResponse.User getUser(){
		if(mUser == null){
			if(!TextUtils.isEmpty(PreferencesStorageUtil.getToken(this))){
				mUser = GsonUtil.fromJson(PreferencesStorageUtil.getUserBean(this), UserResponse.User.class);
			}
		}
		return mUser;
	}

	public QiniuSDK getQiniuSDK(){
		return mQiniuSDK;
	}

	public RestClient getRestClient(){
		return mRestClient;
	}

	//登录后需要刷新token
	public void refreshRestClient(String token){
		mRestClient = new RestClient(token, user_agent);
	}

	public static MFPApplication getInstance(){
		return sInstance;
	}

	/**
	 * Get the event dispatcher.
	 *
	 * @return The event dispaccctcher.
	 */
	public EventDispatcher getEventDispatcher() {
		return mEventDispatcher;
	}

	/**
	 * Get the controller.
	 *
	 * @return The controller.
	 */
	public EventController getEventController() {
		return mEventController;
	}


}
